<?php
/**
 * 折扣模型
 * 
 * @version $Id: Rate.php 264 2012-04-13 03:06:48Z linsir123 $
 */
class modelRate
{
	/**
	 * @var 采集地址
	 */
	public $format;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		App::V('htmldom');
		
		$this->format = "http://s.taobao.com/search?q=%s";
		$this->format .= "&sort=%s";
		$this->format .= "&s=%d";
		$this->format .= "&tab=promotion&style=grid";
	}
	
	/**
	 * 
	 */
	public function getList($cId = null, $keyword = null, $sort = null, $p = null)
	{
		$keyword = iconv("UTF-8", "GB2312", $keyword);
		$url = sprintf($this->format, $keyword, $sort, $p);
		
		///
		$num = 0;
		while (++$num <= 3) {
			$content = file_get_contents($url);
			if ( ! empty($content)) {
				$dom = str_get_html($content);
				$list = $dom->find('div.list-content ul li.list-item');
				if (count($list) > 0) 
					break;
			}
		}
		
		///
		$num = 0;
		$iids = array();
		$data = array();
		foreach($list as $v) {
			$a = $v->find('h3 a', 0);
			$href = $a->href;
			$tmp = parse_url($href);
			parse_str($tmp['query'], $tmp);
			$iid = trim($tmp['id']);
			if (empty($iid) || $num++ >36) 
				continue;
				
			///
			$row = array('title'=>$this->_iconv($a->innertext));
			
			///
			$li = $v->find('li.rate', 0);
			$tmp = explode("<br>", $this->_iconv($li->innertext));
			$row['rate'] = $tmp[0];
			
			///
			$i = 0;
			$em = $v->find('li.price em');
			foreach ($em as $e) 
				$row['price'.$i++] = $e->innertext;
				
			///
			$iids[] = $iid;
			$data['iid_'.$iid] = $row;
		}
		
		$list = M::item()->taobaokeByIids($iids, false);
		$count = count($list);
		$tmp = $count%4;
		if ($tmp > 0) 
			array_splice($list, $count-$tmp, $tmp);
			
		foreach ($list as $k => $v) {
			$tmp = $data['iid_'.$v['num_iid']];
			$v = array_merge($v, $tmp);
			$list[$k] = $v;
		}
		
		return $list;
	}
	
	/**
	 * 
	 */
	private function _iconv($str)
	{
		return iconv("GB2312", "UTF-8", $str);
	}
}
